package logger

import (
	"fmt"
	"os"
	"path"
	"runtime"
	"time"
)

func GetLineInfo() (fileName string, funcName string, lineNum int) {
	pc, file, line, ok := runtime.Caller(4)
	if ok {
		fileName = file
		funcName = runtime.FuncForPC(pc).Name()
		lineNum = line
	}
	return
}

func writeLog(level int, format string, args ...interface{}) (logData *LogData) {
	now := time.Now()
	nowString := now.Format("2006-01-02 15:04:05")
	levelString := getLevelText(level)
	fileName, funcName, lineNum := GetLineInfo()
	fileName = path.Base(fileName)
	funcName = path.Base(funcName)
	msg := fmt.Sprintf(format, args...)
	logData = &LogData{
		Message:     msg,
		TimeString:  nowString,
		LevelString: levelString,
		FileName:    fileName,
		FuncName:    funcName,
		LineNum:     lineNum,
		WarnAndFatal: false,
	}
	if level == LogLevelWarn || level == LogLevelError || level == LogLevelFatal {
		logData.WarnAndFatal = true
	}
	return
	//fmt.Fprintf(logFile, "%s [%s] (%s %s:%d) %s\n", nowString, levelString, fileName, funcName, lineNum, msg)
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}